const express = require('express');
const app = express();
const PORT = 3000;

app.use(express.json());

// 初始用户（明文密码）
const users = {
    dcsgo: '123456',
    alice: 'alice123',
    bob: 'bob666'
};

// 设备列表
const devices = [
    { name: '红外传感器', img: 'app.media.st118', state: '在线' },
    { name: '超声波传感器', img: 'app.media.hc_sr04', state: '在线' }
]

/* 注册 */
app.post('/register', (req, res) => {
    const { username, password } = req.body;
    if (!username || !password) {
        return res.json({ code: 400, data: null, message: '缺少用户名或密码' });
    }
    if (users[username]) {
        return res.json({ code: 409, data: null, message: '用户名已存在' });
    }
    users[username] = password;
    return res.json({ code: 200, data: { username }, message: '注册成功' });
});

/* 登录 */
app.post('/login', (req, res) => {
    const { username, password } = req.body;
    if (!username || !password) {
        return res.json({ code: 400, data: null, message: '缺少用户名或密码' });
    }
    if (users[username] !== password) {
        return res.json({ code: 401, data: null, message: '用户名或密码错误' });
    }
    return res.json({ code: 200, data: { username }, message: '登录成功' });
});

// 红外触发状态  true/false
app.get('/sensor/infrared', (_req, res) => {
    const triggered = Math.random() > 0.5;   // 50% 概率
    return res.json({ code: 200, data: { triggered }, message: 'ok' });
});

// 超声波测距  10.0 ~ 300.0 cm
app.get('/sensor/ultrasonic', (_req, res) => {
    const distance = +(Math.random() * 290 + 10).toFixed(1); // 保留 1 位小数
    return res.json({ code: 200, data: { distance }, message: 'ok' });
});

app.get('/device/list', (req, res) => {
    return res.json({code:200,data:devices,message:'ok'})
});

// 启动
app.listen(PORT, () => console.log(`Server running at http://localhost:${PORT}`));